<?php

namespace App\Listeners\V1;

use App\Events\AppEvent;
use App\Helpers\Logger\SLogger;
use App\Models\Factory\InviteFactory;
use App\Models\Orm\UserIncome;
use Illuminate\Queue\InteractsWithQueue;
use App\Listeners\AppListener;
use App\Models\Factory\DeliveryFactory;
use App\Models\Factory\UserFactory;
use DB;


/**
 * 渠道统计事件监听
 * Class UserRegCountListener
 * @package App\Listeners\V1
 */
class UserRegCountListener extends AppListener
{

    use InteractsWithQueue;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  AppEvent  $event
     * @return void
     */
    public function handle(AppEvent $event)
    {


        $channel = $event->data;


//        DB::beginTransaction();
	    try
	    {

	        //判断邀请码是否真实有效
            if(!is_numeric($channel['invite_code'])){
                SLogger::getStream()->info('邀请码错误');
                return false;
            }

            if($channel['invite_code'] - 190002 < 0){
                SLogger::getStream()->info('邀请码错误');
                return false;
            }
            //邀请人的id
            $inviteUser =UserFactory::getUserById($channel['invite_code'] - 190002);
            if(empty($inviteUser))
            {
                SLogger::getStream()->info('邀请码错误');
                return false;
            }


            //拿到用户的id
            $user = UserFactory::getUserByMobile($channel['phone']);

            $income = UserIncome::FIRSTINCOME;
            //开始送金币(给直接邀请人)
            InviteFactory::addUserIncome($inviteUser->id,$income);

            $inviteUser -> total += $income;

            $inviteUser -> save();


            //插入邀请表
            InviteFactory::addInviteUser($user->id,$inviteUser->id);

            $user->invite_user_id = $inviteUser->id;
            $user ->save();

            //开始写个递归,查找邀请的pid,然后送金币
            InviteFactory::findPid($inviteUser->id,UserIncome::SECONDINCOME,$handle =0);



	    }
	    catch (\Exception $e)
	    {
//		    DB::rollBack();
//
		    SLogger::getStream()->error('注册渠道统计失败');
            SLogger::getStream()->error($e);

        }
	    return false;



    }

}
